/**
 * Copyright (c) 2017, 西安星沙网络科技-版权所有
 *
 * Licensed under the GNU Lesser General Public License (LGPL) ,Version 3.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.gnu.org/licenses/lgpl-3.0.txt
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.waleychain.exchange.consumer.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import cn.waleychain.exchange.consumer.shiro.LoginAuthToken;
import cn.waleychain.exchange.core.entity.TokenEntity;
import cn.waleychain.exchange.core.logger.LoggerHelper;
import cn.waleychain.exchange.core.result.DefaultResult;
import cn.waleychain.exchange.core.result.IBaseResult;
import cn.waleychain.exchange.core.result.RetResultCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import springfox.documentation.annotations.ApiIgnore;

/**
 * token相关控制
 * @author chenx
 * @date 2017年8月11日 下午3:27:39
 * @version 1.0 
 */
@Api(description = "token管理相关")
@RestController
@RequestMapping("api/auth")
public class TokenController extends BaseController {

	private static final Logger mLog = LoggerFactory.getLogger(TokenController.class);
	
	@RequestMapping(value = "/login", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@ApiOperation(value = "用户登录", notes = "用户登录，URL: http://{ip}:{port}/{projectName}/api/auth/login", httpMethod = "POST", response = DefaultResult.class)
	public IBaseResult login (
			@ApiParam(value = "用户账号", required = true) @RequestParam String loginName, 
			@ApiParam(value = "密码", required = true) @RequestParam String loginPass,
			@RequestHeader String subSystemCode) throws Exception {

		try {
			Subject subject = SecurityUtils.getSubject();

			// 组合系统码和登录名称
			LoginAuthToken token = new LoginAuthToken(loginName, loginPass, subSystemCode);
			subject.login(token);

			TokenEntity tokenEntity = (TokenEntity) subject.getPrincipals().getPrimaryPrincipal();
			
			tokenEntity.setToken(subject.getSession().getId());
			tokenEntity.setSubSystemCode(subSystemCode);

			return DefaultResult.buildSuccessResult(tokenEntity);
		} catch (UnknownAccountException e) {
			return DefaultResult.buildFailedResult(RetResultCode.E20001);
		} catch (IncorrectCredentialsException e) {
			return DefaultResult.buildFailedResult(RetResultCode.E20001);
		} catch (LockedAccountException e) {
			return DefaultResult.buildFailedResult(RetResultCode.E20006);
		} catch (AuthenticationException e) {
			return DefaultResult.buildFailedResult(RetResultCode.E20001);
		} catch (Exception e) {
			LoggerHelper.printLogError(mLog, e, "用户登录");
		}

		return DefaultResult.buildFailedResult();
	}

	/**
	 * 未登录，shiro应重定向到登录界面，此处返回未登录状态信息由前端控制跳转页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/unauth")
	@ResponseBody
	@ApiIgnore
	public Object unauth() {
		return DefaultResult.buildFailedResult(RetResultCode.E10002);
	}
	
	@RequestMapping(value="/logout", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@ApiOperation(value = "退出登录", notes = "退出登录，URL: http://{ip}:{port}/{projectName}/api/auth/logout", httpMethod = "DELETE", response = DefaultResult.class)
	public IBaseResult logout (
			@RequestHeader String Authorization) throws Exception {
		
		try {
			SecurityUtils.getSubject().logout();
			return DefaultResult.buildSuccessResult();
		} catch (Exception e) {
			LoggerHelper.printLogError(mLog, e, "退出登录");
		}
		
		return DefaultResult.buildFailedResult();
	}
	
}
